const app = getApp();
var WxParse = require('../../../wxParse/wxParse/wxParse.js');

Page({
  data: {
    isCollected: false, // 收藏状态
    content: '',
    article: null,
    user_id: null, // 用户ID
  },

  onLoad(options) {
    this.setData({
      user_id: app.globalData.userInfo.id,
      url: app.globalData.URL
    });
    console.log(options)
    const id = options.id;
    this.fetchArticleData(id);
    this.checkIfCollected(id);
  },

  fetchArticleData(id) {
    wx.request({
      url: this.data.url + 'heartmark/selectById', // 获取测评详细信息
      data: { id: id },
      success: (res) => {
        const result = res.data.data;
        WxParse.wxParse('content', 'html', result.simplyIntroduce, this, 5);
        this.setData({ article: result });
      }
    });
  },

  checkIfCollected(articleId) {
    wx.request({
      url: `${this.data.url}/mytest/find`, // 根据 user_id 获取 test_id 列表
      method: 'GET',
      data: { id: this.data.user_id },
      success: (res) => {
        const testData = res.data.data;
        if (testData && Array.isArray(testData.list)) {
          const numericArticleId = Number(articleId); // 转换 articleId 类型
          console.log("Converted articleId:", numericArticleId);
          console.log("Test IDs List:", testData.list);
          console.log("Is Collected:", testData.list.includes(numericArticleId));
          
          this.setData({ isCollected: testData.list.includes(numericArticleId) });
        } else {
          console.error("Unexpected data format:", testData);
          this.setData({ isCollected: false });
        }
      },
      fail: (err) => {
        console.error("Request failed:", err);
        this.setData({ isCollected: false });
      }
    });
  },
  
  
  

  onCollect() {
    const { id } = this.data.article;
    this.animateButton();

    if (this.data.isCollected) {
      this.cancelCollect(id);
    } else {
      this.collect(id);
    }
  },

  collect(id) {
    wx.request({
      url: `${this.data.url}mytest/insert`,
      method: 'POST',
      data: { userId: this.data.user_id, testId: id },
      success: () => {
        this.setData({ isCollected: true });
      }
    });
  },

  cancelCollect(id) {
    wx.request({
      url: `${this.data.url}mytest/deleteByAllId`,
      method: 'POST',
      data: { userId: this.data.user_id, testId: id },
      success: () => {
        this.setData({ isCollected: false });
      }
    });
  },

  animateButton() {
    const animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-in-out'
    });

    animation.scale(1.1).step();
    this.setData({ animationData: animation.export() });

    setTimeout(() => {
      animation.scale(1).step();
      this.setData({ animationData: animation.export() });
    }, 300);
  }
});
